from cron_converter import Cron
import json5, time, datetime, ssl, schedule, functools
from lxml import etree
import sqlite3, os, feedparser, linecache, re
from common import Config, DbHelper


class Faq(Config):
    def __init__(self):
        self.db = DbHelper()
        self.faq_config = self.load_config('faq.json5')

    def gen_question_rss(self):
        for item_config in self.faq_config:
            self.gen_question_rss_item(item_config)
        self.__save_config()

    def gen_question_rss_item(self, item_config):
        if not self.__check_cron(item_config):
            return

        curr_line = item_config['curr_line']
        faq_file = item_config['file']
        
        line_num = int(curr_line) if curr_line else 1

        # if os.path.exists('.faq'):
        #     with open('.faq','r', encoding='utf8') as fp:
        #         line_text = fp.readline()
        #         line_num = int(line_text) if line_text else 1
        # else:
        #     line_num = 1

        line_num, title, link, description = self.__get_next_question(faq_file, line_num)
        if not title:
            return
        ymd = datetime.datetime.now().strftime('%Y%m%d')
        link = link if link else f'http://faq/{ymd}/{faq_file}/{line_num}'
        title = title + ' ' +ymd
        self.db.insert_rss_item(title, link, description=description)
        print("QA Inserted： "+title)
        item_config['curr_line'] = line_num
        

    def __get_next_question(self, faq_file, line_num: int):
        print(f"QA Load： {faq_file}, num={line_num+1}")
        title=''; link = ''; description = ''
        while True:
            line_num = line_num+1
            line = linecache.getline(faq_file, line_num)
            line = line.rstrip() if len(line)>0 else None
            if line==None:  # 文件尾部
                line_num = 0 # 再次从第1行开始
                continue
            elif line=='' or line.startswith('#'): # 空行，目录标题
                if title:
                    break   # 目录标题，title不为空，找到title
                else:
                    continue    # 目录标题，title为空，跳到下一行
            elif line.startswith('  '):   # 下一级，内容
                line = line.strip()
                line = line[1:] if line.startswith('- ') else line
                if title and line:
                    description = description + '<li>' + line.strip() + '</li>'
            elif line.startswith('- '):
                line = line[1:].strip()
                if title:
                    break
                matchLink = re.match( r'.*\[(.+)\]\((.+?)\).*', line, re.M|re.I)
                if matchLink:
                    title = matchLink.group(1)
                    link = matchLink.group(2)
                else:
                    title = line
                    link = ''
        return (line_num-1, title, link, '<h3>'+title+'<h3><ul>'+description+'</ul>')

    def __save_config(self):
        with open("faq.json5", mode='w', encoding='utf-8') as fp:
            fp.write(json5.dumps(self.faq_config))
                
    def __check_cron(self, item_config):
        cron_str = item_config['cron']
        diff = self.getDiff_prevCron_now(cron_str)
        return not diff or (diff>0 and diff<10*60)  # 10分钟

if __name__ == '__main__':
    faq = Faq()
    faq.gen_question_rss()